#include "cmysql.h"

MYSQL *getnewconn(void)
{
    MYSQL *conn;
    conn = mysql_init(NULL);
    if (conn == NULL)
    {
        fprintf(stderr, "mysql_init() failed\n");
        return NULL;
    }

    if (mysql_real_connect(conn, "localhost", "wxp", "123", "project", 0, NULL, 0) == NULL)
    {
        fprintf(stderr, "%s\n", mysql_error(conn));
        mysql_close(conn);
        return NULL;
    }
    return conn;
}
MYSQL_RES *resultofquery(MYSQL *MYSQL, char *table, char *field)
{
    MYSQL_RES *res;
    char query[1024];
    if (table != NULL && field != NULL)
    {
        sprintf(query, "SELECT * FROM %s where %s", table, field);
    }
    if (table != NULL && field == NULL)
    {
        sprintf(query, "SELECT * FROM %s", table);
    }
    if (mysql_query(MYSQL, query) != 0)
    {
        fprintf(stderr, "%s\n", mysql_error(MYSQL));
        mysql_close(MYSQL);
        return NULL;
    }
    res = mysql_use_result(MYSQL);
    if (res == NULL)
    {
        printf("mysql_use_result() failed\n");
        mysql_close(MYSQL);
        return NULL;
    }
    return res;
}
void insertdata(MYSQL *MYSQL,  char *table,  char *field,  char *value)
{
    char query[1024];
    sprintf(query, "INSERT INTO %s (%s) VALUES (%s)", table, field, value);
    printf("Query: %s\n", query);
    if (mysql_query(MYSQL, query) != 0)
    {
        fprintf(stderr, "%s\n", mysql_error(MYSQL));
        mysql_close(MYSQL);
        return;
    }
    printf("Data inserted successfully");
}
void deletedata(MYSQL *MYSQL,  char *table,  char *value)
{
    char query[1024];
    sprintf(query, "DELETE FROM %s WHERE %s", table, value);
    if (mysql_query(MYSQL, query) != 0)
    {
        fprintf(stderr, "%s\n", mysql_error(MYSQL));
        mysql_close(MYSQL);
        return;
    }
}
void updatedata(MYSQL *MYSQL,  char *table, char *field)
{
    char query[1024];
    sprintf(query, "UPDATE %s SET %s", table, field);
    if (mysql_query(MYSQL, query) != 0)
    {
        fprintf(stderr, "%s\n", mysql_error(MYSQL));
        mysql_close(MYSQL);
        return;
    }
}
